/**
 * @author Alejandro
 */

package com.biblioteca.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import biblioteca.Recurso;

/**
 * Servlet implementation class RecursosServlet
 * 
 */
@WebServlet("/adminRecursos.servlet")
public class RecursosServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @author Alejandro
     * @see HttpServlet#HttpServlet()
     */
    public RecursosServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	@SuppressWarnings("unchecked")
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String accion = request.getParameter("accion");
		System.out.println("Accion: " + accion);
		List<Recurso> listaR = (List<Recurso>)request.getSession().getAttribute("listaRecurso");
		Recurso recurso = new Recurso();
		recurso.setTitulo(request.getParameter("titulo"));
		recurso.setAutor(request.getParameter("autor"));
		recurso.setMateria(request.getParameter("materia"));
		recurso.setCodigo(Integer.parseInt(request.getParameter("codigo")));
		
		//definimos las funciones al accionar los botones
		//guarda la lista si el titulo coincide
		if (accion.equals("guardar")) {
			listaR.add(recurso);
			
			response.sendRedirect("recursos.jsp");
			
		} else if (accion.equals("actualizar")) {
			//actualiza la lista si el titulo coincide
			for (Recurso obj : listaR) {
				if (obj.getTitulo().equals(recurso.getTitulo())) {
					obj.setAutor(recurso.getAutor());
					obj.setMateria(recurso.getMateria());
					obj.setCodigo(recurso.getCodigo());
					response.sendRedirect("recursos.jsp");
				}
			}
		} else if(accion.equals("eliminar")){
			//elimina la lista si el titulo coincide
			Iterator<Recurso> iter = listaR.iterator();
			while(iter.hasNext()){
			Recurso list1 = iter.next();
			if(list1.getTitulo().equals(recurso.getTitulo())){
				listaR.remove(list1);
				break; }
		}
			response.sendRedirect("recursos.jsp");
			}
			
		

	}

	
	
	
	
		
	

}
